import { Tabs, message } from 'antd'
import { HomeFilled } from '@ant-design/icons'
import { useEffect, useState } from 'react'
import { searchRoute } from '@/utils'
import { routerArray } from '@/router'
import { useSelector, useDispatch } from '@/store'
import { setTabsList } from '@/store/modules/tabs'
import { HOME_URL } from '@/config/config'
import { useNavigate, useLocation } from 'react-router-dom'
import MoreButton from './components/MoreButton.js'
import './index.less'

export default function LayoutTabs() {
  const navigate = useNavigate()
  const { pathname } = useLocation()
  const { tabsList } = useSelector((state) => state.tabs)

  const [activeValue, setActiveValue] = useState(pathname)

  const dispatch = useDispatch()

  const addTabs = () => {
    // 获取当前的路由和store存储的tab进行对比，如果没有就添加
    const route = searchRoute(pathname, routerArray)
    const newTabsList = JSON.parse(JSON.stringify(tabsList))

    if (tabsList.every((item) => item.path !== route.path)) {
      newTabsList.push({ title: route.meta.title, path: route.path })
    }
    dispatch(setTabsList(newTabsList))
    setActiveValue(pathname)
  }
  const delTabs = (path) => {
    // 首页不允许删除
    if (path === HOME_URL) {
      return
    }
    // 关闭当前tab后，要navigate到前一个tab,如果前一个tab不在navigate到后一个tab
    if (path === pathname) {
      tabsList.forEach((item, index) => {
        if (item.path === path) {
          const nextPath = tabsList[index + 1] || tabsList[index - 1]
          navigate(nextPath.path)
        }
      })
    }
    message.success('你删除了Tabs标签 😆😆😆')
    //关闭其他tab，把store里面的tab重新更新
    dispatch(setTabsList(tabsList.filter((item) => item.path !== path)))
  }
  const clickTabs = (path) => {
    navigate(path) 
  }
  // 监听路由的变化
  useEffect(() => {
    addTabs()
  }, [pathname])

  return (
    <div className="tabs">
      <Tabs
        activeKey={activeValue}
        hideAdd
        type="editable-card"
        onChange={clickTabs}
        onEdit={(path) => {
          delTabs(path)
        }}
      >
        {tabsList.map((item, index) => {
          return (
            <Tabs.TabPane
              key={item.path}
              tab={
                <span>
                  {item.path == HOME_URL ? <HomeFilled /> : ''}
                  {item.title}
                </span>
              }
              	closable={item.path !== HOME_URL}
            ></Tabs.TabPane>
          )
        })}
      </Tabs>
      <MoreButton delTabs={ delTabs} />
    </div>
  )
}
